package com.resou.reader.assist;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.resou.reader.R;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.utils.CopyUtil;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.view.NetErrorFragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class WebActivity extends ResouBaseActivity {

    public static final String TITLE = "title";
    public static final String URL = "url";
    @BindView(R.id.webView)
    WebView mWebView;

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivBack)
    ImageView ivBack;
    private String url = "";
    BottomSheetDialog bottomSheetDialog;
    String picUrl = "";
    private NetErrorFragment mNetErrorFragment2;

    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    public void retryRefreshData() {
        mWebView.loadUrl(url);
    }

    @Override
    protected void initStatusBar() {

    }

    @Override
    protected void initPresenter() {
    }

    @Override
    protected void initView() {
        showLoading();
        url = getIntent().getStringExtra(URL);
        //设置支持javascript
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setAllowFileAccessFromFileURLs(false);
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 使用localStorage则必须打开
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setGeolocationEnabled(true);
        //WebView.setWebContentsDebuggingEnabled(true);
        mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("tel") || url.contains("mqqapi:")) {
                    return true;
                }
                return false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                ToastUtil.makeShortToast("网络异常");
                showNetErrorView2(R.id.rlContent);
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        if (url.endsWith("helpPages?app=app")) {
            ivBack.setOnClickListener(v -> {
                if (mWebView.getUrl().endsWith("helpPages?app=app")) {
                    finish();
                } else {
                    mWebView.loadUrl(url);
                }
            });
        } else {
            ivBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    } else {
                        finish();
                    }
                }
            });
        }

        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult hitTestResult = mWebView.getHitTestResult();
                if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                        hitTestResult.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
                    // 弹出保存图片的对话框
                    picUrl = hitTestResult.getExtra();
                    bottomSheetDialog.show();
                    return true;
                }
                return false;
            }
        });
        tvTitle.setText(getIntent().getStringExtra(TITLE));
        mWebView.setWebChromeClient(new WebChromeClient() {
                                        @Override
                                        public void onProgressChanged(WebView view, int newProgress) {
                                            super.onProgressChanged(view, newProgress);
                                            if (newProgress == 100) {
                                                dissLoading();
                                                if (NetworkUtils.isNetworkConnected(WebActivity.this)) {
                                                    dismissNetErrorView2();
                                                    if (mWebView != null)
                                                        mWebView.setVisibility(View.VISIBLE);
                                                }
                                            }
                                        }

                                    }

        );
        if (!TextUtils.isEmpty(url)) {

            mWebView.loadUrl(url);
        }
        initBottomDialog();
    }

    private void initBottomDialog() {
        bottomSheetDialog = new BottomSheetDialog(this, R.style.BottomDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.layout_bottomsheet, null);
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.setCanceledOnTouchOutside(true);
        TextView save = view.findViewById(R.id.tvSave);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveScanPic(picUrl);
                bottomSheetDialog.cancel();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.cancel();
            }
        });
    }

    public static void startActivity(Context context, String url, String title) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(URL, url);
        intent.putExtra(TITLE, title);
        context.startActivity(intent);
    }

    private void saveScanPic(String url) {
        Observable.create(
                new Observable.OnSubscribe<File>() {
                    @Override
                    public void call(Subscriber<? super File> subscriber) {
                        try {
                            RequestOptions options = new RequestOptions();
                            options.format(DecodeFormat.PREFER_RGB_565);
                            subscriber.onNext(Glide.with(getApplicationContext()).load(url).apply(options).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get());
                            subscriber.onCompleted();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<File>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(File file) {
                        try {
                            CopyUtil.saveBmpGallery(getApplicationContext(), BitmapFactory.decodeStream(new FileInputStream(file)), "热搜");
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 显示网络异常视图
     *
     * @param resId
     */
    public void showNetErrorView2(int resId) {
        if (mNetErrorFragment2 == null) {
            mNetErrorFragment2 = new NetErrorFragment(new NetErrorFragment.OnClick() {
                @Override
                public void onClick() {
                    retryRefreshData();
                }
            });
        }
        mNetErrorFragment2.show(resId, getSupportFragmentManager());
    }

    /**
     * 关闭无网络页码
     */
    public void dismissNetErrorView2() {
        if (mNetErrorFragment2 != null) {
            mNetErrorFragment2.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if( mWebView!=null) {

            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }

            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();

        }
    }
}
